package com.twh.www.controller;

import com.twh.www.entity.WnUser;
import com.twh.www.service.SmsService;
import com.twh.www.service.WnUserService;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import org.springframework.util.DigestUtils;
import com.twh.www.service.LoginService;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping("/user")
public class UserController {

    @Autowired
    WnUserService wnUserService;

    @Autowired
    private LoginService loginService;
   
    @Autowired
    private SmsService smsService;

    @GetMapping("/login")
    public String login() {
        return "login";
    }
    @GetMapping("/register")
    public String register() {
        return "register";
    }
    @GetMapping ("/admin")
        public String admin() {
        return "admin";
    }

    @PostMapping("/login")
    public String login(@RequestParam String loginType,
                        @RequestParam(required = false) String account,
                        @RequestParam(required = false) String password,
                        @RequestParam(required = false) String phone,
                        @RequestParam(required = false) String email,
                        @RequestParam(required = false) String code,
                        HttpSession session) throws IOException {
        WnUser user = null;
        if ("PASSWORD".equals(loginType)) {
            user = loginService.login("PASSWORD", account, password);
        } else if ("PHONE".equals(loginType)) {
            // 校验验证码
            String realCode = (String) session.getAttribute("phoneCode:" + phone);
            if (realCode == null || code == null || !realCode.equals(code)) {
                return "redirect:/user/login?msg=" + URLEncoder.encode("验证码错误", "UTF-8");
            }
            user = loginService.login("PHONE", phone);
        } else if ("EMAIL".equals(loginType)) {
            user = loginService.login("EMAIL", email);
        }
        if (user == null) {
            return "redirect:/user/login?msg=" + URLEncoder.encode("登录失败", "UTF-8");
        }
        session.setAttribute("LoginUser", user);
        return "redirect:/";
    }

    @PostMapping("/ajaxLogin")
    @ResponseBody
    public Map<String, Object> ajaxLogin(
            @RequestParam String loginType,
            @RequestParam(required = false) String account,
            @RequestParam(required = false) String password,
            @RequestParam(required = false) String phone,
            @RequestParam(required = false) String email,
            @RequestParam(required = false) String code,
            HttpSession session) throws IOException {
        Map<String, Object> result = new HashMap<>();
        WnUser user = null;
        if ("PASSWORD".equals(loginType)) {
            if (account == null || account.isEmpty()) {
                result.put("success", false);
                result.put("msg", "请输入用户名");
                return result;
            }
            if (password == null || password.isEmpty()) {
                result.put("success", false);
                result.put("msg", "请输入密码");
                return result;
            }
            user = loginService.login("PASSWORD", account, password);
            if (user == null) {
                if (wnUserService.getUserByAccount(account) == null) {
                    result.put("success", false);
                    result.put("msg", "用户名不存在");
                } else {
                    result.put("success", false);
                    result.put("msg", "密码错误");
                }
                return result;
            }
        } else if ("PHONE".equals(loginType)) {
            if (phone == null || phone.isEmpty()) {
                result.put("success", false);
                result.put("msg", "请输入手机号");
                return result;
            }
            user = loginService.login("PHONE", phone);
            if (user == null) {
                result.put("success", false);
                result.put("msg", "手机号未注册");
                return result;
            }
            String realCode = (String) session.getAttribute("phoneCode:" + phone);
            if (realCode == null || code == null || !realCode.equals(code)) {
                result.put("success", false);
                result.put("msg", "验证码错误");
                return result;
            }

        } else if ("EMAIL".equals(loginType)) {
            if (email == null || email.isEmpty()) {
                result.put("success", false);
                result.put("msg", "请输入邮箱");
                return result;
            }
            user = loginService.login("EMAIL", email);
            if (user == null) {
                result.put("success", false);
                result.put("msg", "邮箱未注册");
                return result;
            }
        }
        // 登录成功
        session.setAttribute("LoginUser", user);
        result.put("success", true);
        return result;
    }

    
    /**
     * 验证用户名格式
     * @param username 用户名
     * @return 是否有效
     */
    private boolean isValidUsername(String username) {
        if (username == null || username.length() < 5 || username.length() > 10) {
            return false;
        }
        // 不能以数字开头
        if (Character.isDigit(username.charAt(0))) {
            return false;
        }
        // 只能包含字母和数字
        return username.matches("^[a-zA-Z0-9]+$");
    }

    /**
     * 验证密码格式
     * @param password 密码
     * @return 是否有效
     */
    private boolean isValidPassword(String password) {
        if (password == null || password.length() < 5 || password.length() > 10) {
            return false;
        }
        // 必须以大写字母开头
        if (!Character.isUpperCase(password.charAt(0))) {
            return false;
        }
        // 只能包含字母和数字
        return password.matches("^[a-zA-Z0-9]+$");
    }

    @PostMapping("/registerWithFile")
    @ResponseBody
    public String registerWithFile(@RequestParam String account,
                                  @RequestParam String password,
                                  @RequestParam String telphone,
                                  @RequestParam String email,
                                  @RequestPart(required = false) MultipartFile avatar) throws IOException {
        try {
            // 验证用户名
            if (!isValidUsername(account)) {
                return "用户名只能包含字母和数字，且不能以数字开头，长度为6到10位";
            }

            // 验证密码
            if (!isValidPassword(password)) {
                return "密码必须以大写字母开头，且只能包含字母和数字，长度为6到10位";
            }

            boolean result = wnUserService.insertUser(account, password, telphone, email, avatar);
            if (result) {
                return "success";
            } else {
                return "fail";
            }
        } catch (IllegalArgumentException e) {
            return e.getMessage();
        } catch (Exception e) {
            e.printStackTrace();
            return "系统错误，请稍后再试";
        }
    }

    @GetMapping("/logout")
    public String logout(HttpSession session) {
        // Destroy the session
        session.removeAttribute("LoginUser");
        return  "redirect:/user/login";
    }
    
    @GetMapping("/myAccount")
    public String myAccount(HttpSession session, Model model) {
        WnUser user = (WnUser) session.getAttribute("LoginUser");
        if (user == null) {
            return "redirect:/user/login";
        }
        model.addAttribute("user", user);
        return "myAccount";
    }
    
    @PostMapping("/updateUserInfo")
    @ResponseBody
    public String updateUserInfo(@RequestParam String account,
                               @RequestParam String telphone,
                               @RequestParam String email,
                               @RequestParam(required = false) String password,
                               @RequestPart(required = false) MultipartFile avatar,
                               HttpSession session) throws IOException {
        WnUser user = (WnUser) session.getAttribute("LoginUser");
        if (user == null) {
            return "请先登录";
        }
        
        try {
            // 检查新账号是否已被其他用户使用
            WnUser existingUser = wnUserService.getUserByAccount(account);
            if (existingUser != null && !existingUser.getId().equals(user.getId())) {
                return "该账号已被其他用户使用";
            }
            
            // 验证用户名
            if (!isValidUsername(account)) {
                return "用户名只能包含字母和数字，且不能以数字开头，长度为6到10位";
            }

            // 验证密码
            if (password != null && !password.isEmpty() && !isValidPassword(password)) {
                return "密码必须以大写字母开头，且只能包含字母和数字，长度为6到10位";
            }
            
            // 如果有上传新头像，保存并更新路径
            if (avatar != null && !avatar.isEmpty()) {
                String avatarPath = wnUserService.saveAvatar(avatar);
                user.setAvatar(avatarPath);
            }
            
            // 更新其他信息
            user.setAccount(account);
            user.setTelphone(telphone);
            user.setEmail(email);
            
            // 如果提供了新密码，则更新密码
            if (password != null && !password.isEmpty()) {
                user.setPassword(DigestUtils.md5DigestAsHex(password.getBytes()));
            }
            
            boolean result = wnUserService.updateUserInfo(user);
            if (result) {
                // 更新session中的用户信息
                session.setAttribute("LoginUser", user);
                return "success";
            } else {
                return "更新失败，请稍后再试";
            }
        } catch (IllegalArgumentException e) {
            return e.getMessage();
        } catch (Exception e) {
            e.printStackTrace();
            return "系统错误，请稍后再试";
        }
    }

    @PostMapping("/sendCode")
    @ResponseBody
    public String sendCode(@RequestParam String phone, HttpSession session) {
        // 生成4位随机验证码
        String code = String.valueOf((int)((Math.random() * 9 + 1) * 1000));
        String[] datas = {code, "5"}; // 5分钟有效
        boolean success = smsService.sendTemplateSMS(phone, datas);
        if (success) {
            // 将验证码存入session，key为phoneCode:手机号
            session.setAttribute("phoneCode:" + phone, code);
            return "success";
        } else {
            return "fail";
        }
    }
}
